package com.live.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	public static DataSource  dataSource = null;
	
	static {
		dataSource =  new ComboPooledDataSource();
		
	}public static void ininDataSource(){
		dataSource =  new ComboPooledDataSource();
	}

	public static Connection getConnection() {
		Connection conn = null;
		
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {	
			e.printStackTrace();
		}
		return conn;
	}

	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static boolean executeUpdate(String sql, Object... param) {
		boolean flag = true;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
			ps.setObject(i + 1, param[i]);
			}
			ps.executeUpdate();
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		} finally {
			close(conn, ps, null);
		}
			return flag;
	}

	public static  Object executeQuery(String sql, RowMapper mapper,
			Object... param) {
		Object result = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				ps.setObject(i + 1, param[i]);
			}
			rs = ps.executeQuery();
			result = mapper.mapper(rs);
		} catch (Exception e) {
			
			e.printStackTrace();
		} finally {
			close(conn, ps, rs);
		}
		return result;
	}
	public static String getSimpleTimeStr(Date date) {
		if(date == null) {
			return "";
		}
	
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		return sdf.format(date);
	}
	/**
	 * convert date string to date
	 * 
	 * @param dateStr
	 * @return
	 * @throws java.text.ParseException
	 */
	public static Date parseDate(String dateStr) throws ParseException {
		if(StringUtil.isNullOrEmpty(dateStr)) {
			return null;
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		return  sdf.parse(dateStr);
	}
	
}

